<!--
 * 存储源
 * @author luguoxiang
 * @date 2024-03-01
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
-->
<template>
  <edit-container ref="containerRef" v-bind="containerConfig">
    <lg-form ref="formRef" v-loading="loading" :schema="schema" v-bind="formConfig">
      <template #append>
        <t-form-item label="">
          <t-button :loading="loading" @click="test">连接测试</t-button>
        </t-form-item>
      </template>
    </lg-form>
  </edit-container>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { EditContainer, useEditContainer } from '@/components';
import { LgForm } from '@/soar';
import api, { subject } from './api';
import schema, { StorageSource } from './schema';

const emits = defineEmits(['ok']);

const containerRef = ref();
const formRef = ref();
const { containerConfig, formConfig, loading, open, data } = useEditContainer<StorageSource>({
  header: subject,
  containerRef,
  formRef,
  getData: (params: any) => api.detail(params.id),
  onOk: async ({ values, data, params, isUpdate, changed }) => {
    if (changed) {
      values.id = data.id;
      if (values.accessKey === '******') {
        delete values.accessKey;
      }
      if (values.secretKey === '******') {
        delete values.secretKey;
      }
      await api.saveOrUpdate(values, isUpdate);
      emits('ok', values);
    }
  },
  containerProps: {
    width: '900px',
  },
  formProps: {
    gridProps: {
      width: 300,
    },
  },
  data: {
    pathStyleAccess: true,
    status: 0,
  },
});

async function test() {
  await formRef.value?.validate();
  const values = formRef.value?.getData();
  values.id = data.value.id;
  if (values.accessKey === '******') {
    delete values.accessKey;
  }
  if (values.secretKey === '******') {
    delete values.secretKey;
  }
  api.test(values).finally(() => (loading.value = false));
  loading.value = true;
}

defineExpose({ open });
</script>
